<?php

/**
 * @Author:      lyt
 * @DateTime:    2016-10-25 13:57:25
 * @Description: 用于订单的代付接口
 */
class ScsOrderPayotherController extends BaseController
{
   /**
    * @Author:      lyt
    * @DateTime:    2016-10-25 13:57:52
    * @Description: 订单是否允许代付
    */
    public function isCanOtherPay(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order=Orders::find(Input::get('order_id'));
            if(is_null($order)){//服务单才判断
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            // if($order->place!=2){//如果不是到店
            //     $response = Lang::get("scs_error.order_notexiet_40000");
            //     break;
            // }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;

            }
            
            if($order->status!=1420||$order->order_type==2){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_status_error_40024");
                break;
            }            
            if(Orders::isOutReturnOrders($order->order_id)){//是否有 未完成的出退库 记录
                $response = Lang::get("scs_error.order_out_return_error_40034");
                break;
            }
            if(in_array($order->status,array(1117,1217,1417))){//是否已结算
                $response = Lang::get("scs_error.order_status_error_40040");
                break;
            } 
            $op=OrderProduct::where("order_id",$order->order_id)->where("product_type","service_card")->where("status",1)->first();      
            if($op){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_otherpay_error_42007");
                break;
            }

            $user=Users::where("id",$order->user_id)->first();
            if($user->type==2||$user->id==1000000000){
                $response = Lang::get("scs_error.order_otherpay_error_42000");
                break;
            }
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "isCanOtherPay", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    
    /**
     * @Author:      lyt
     * @DateTime:    2016-10-25 14:48:55
     * @Description: 获取该车牌号吓的企业车辆信息
     */
    public function checkCarNoPay(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'car_no'=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $uci=UserCarInfo::leftJoin("users","users.id","=","user_car_info.user_id")
            ->leftJoin('user_account','user_account.user_id','=','users.id')
            ->where("user_car_info.status",1)->where("users.type",2)->
            where("users.status",1)->where("user_car_info.car_no",Input::get("car_no"))
            ->select('users.id','users.phone','users.real_name','user_account.account_no','user_account.balance','user_account.credit',"user_car_info.id as use_car_id")->get();
            if(sizeof($uci)==0){
                $response = Lang::get("scs_error.order_otherpay_checkno_error_42001");
                break;
            }
            foreach($uci as $_uci){
                $cc=DB::select("SELECT  sum(balance) as balance ,sum(credit) as credit,user_id FROM user_account_details WHERE acount_type = 3 and user_id=".$_uci->id);
                $bb=DB::select("SELECT  sum(balance) as balance ,sum(credit) as credit,user_id FROM user_account_details WHERE acount_type != 3 and user_id=".$_uci->id);
                $_uci->balance=bcdiv($bb[0]->balance,100,2);
                $_uci->credit=bcdiv(($cc[0]->credit+$cc[0]->balance),100,4);
            }
            $sc=SCUser::where('status',1)->where('shop_id',$sc_user->shop_id)->where('title',1)->select('id','real_name')->get();            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("pay_array"=>$uci,"sc_check"=>$sc));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "checkCarNoPay", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

   /**
    * @Author:      lyt
    * @DateTime:    2016-10-25 16:14:27
    * @Description: 代付的发送验证码
    */
    public function otherpaysendMessage(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "id"=>'required',
                "order_id"=>'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order=Orders::find(Input::get('order_id'));
            if(is_null($order)){//服务单才判断
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            $sc=ScUser::find(Input::get("id"));
            if($order->shop_id!=$sc->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            $time_out_default = Config::get("user.time_out_default");

            
            //检查手机号是否下发验证码
            $record = UserCheckCodeUpgrade::where('business_id',Input::get("order_id"))->where("business_type","other_pay")->where("phone",$sc->phone)->first();
            if(!is_null($record)){ //有记录
                //判断是否超时
                if( time() < Common::datetime2Num($record->out_time_at) ){ //没有超过时限
                    try {
                        $sms_send_record_id = Sms::send_message('',$sc->phone,'您好：'.$sc_user->shop->name.'，申请代付业务，订单：'.Input::get("order_id").'，您的授权码为'.$record->check_code);
                    } catch (Exception $e) {
                        Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
                        $response = Lang::get("error.user_sms_check_code_send_error_1003");
                        break;
                    }
                    $response = array(
                        'code' => 0,
                        'msg' => 'ok',
                        'result' => array(
                            'out_time' => Common::datetime2Num($record->out_time_at) - time(),
                        ));
                    break;
                }else{ //超过限时
                    $record->delete();
                }
            }
            //超过时限和没有记录
            //生成验证码
            $check_code = Common::generateCode();
            //调用短信网关发送短信
            try {
                $sms_send_record_id = Sms::send_message('',$sc->phone,'您好：'.$sc_user->shop->name.'，申请代付业务，订单：'.Input::get("order_id").'，您的授权码为'.$check_code);
            } catch (Exception $e) {
                Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_sms_check_code_send_error_1003");
                break;
            }           
            
            $record = new UserCheckCodeUpgrade;
            $record->business_type="other_pay";
            $record->business_id=Input::get("order_id");
            $record->phone=$sc->phone;
            $record->area="";
            $record->check_code=$check_code;
            $record->out_time_at=Common::num2DateTime(time() + $time_out_default);
            $record->send_id=$sms_send_record_id;           
            $record->save();
            
            //组织返回
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => array(
                    'out_time' => $time_out_default,
                )
            );
            
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "otherpaysendMessage", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
    * @Author:      lyt
    * @DateTime:    2016-10-27 15:44:52
    * @Description: 一个并没哟卵用的 接口 把下面的接口验证 拿上来 为前台验证使用 
    */    
    /**
     * @Author:      lyt
     * @DateTime:  2017-06-14 16:45:33
     * @Description: 接口废弃 支付的流程做修改废弃接口
     */
    // public function otherPayBefore(){
    //     $validator = Validator::make(Input::all(),
    //         array(
    //             'token'    => 'required',
    //             "order_id"=>'required',
    //             'pays'=>"required",
    //             "pay_user_id"=>'required',
    //         )
    //     );
    //     $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
    //     do{
    //         if($validator->fails()) {
    //             $response = Lang::get("scs_error.args_error_10000");
    //             $response["result"]=$validator->messages()->all();
    //             break;
    //         }
    //         $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
    //         if(is_null($sc_user)){
    //             break;
    //         }
    //         //验证身份
          
    //         //验证身份完毕
    //         $order=Orders::find(Input::get('order_id'));
    //         $userInfo=Users::find(Input::get("pay_user_id"));
    //         if(is_null($userInfo)||$userInfo->type==1){
    //             $response = Lang::get("scs_error.order_otherpay_payuser_error_42004");
    //             break;
    //         }
    //         if(is_null($order)){
    //             $response = Lang::get("scs_error.order_notexiet_40000");
    //             break;
    //         }
    //         if($order->shop_id!=$sc_user->shop_id){
    //             $response = Lang::get("scs_error.order_note_shop_error_40003");
    //             break;
    //         }
    //         if($order->status!=1216){//订单状态是否为服务结束状态
    //             $response = Lang::get("scs_error.order_status_error_40024");
    //             break;
    //         }            
    //         if(Orders::isOutReturnOrders($order->order_id)){//是否有 未完成的出退库 记录
    //             $response = Lang::get("scs_error.order_out_return_error_40034");
    //             break;
    //         }
    //         if(in_array($order->status,array(1117,1217,1417))){//是否已结算
    //             $response = Lang::get("scs_error.order_status_error_40040");
    //             break;
    //         }           
            
    //         $pays = json_decode(Input::get('pays'),1);
    //         $pay_array=array();
    //         $pay_type=array();
    //         $temp_amount=0;
    //         foreach ($pays as $_pay) {
    //             $date_id=explode(":",$_pay);
    //             $temp_amount+=$date_id[1];
    //             $pay_array[]=array("pay_type"=>$date_id[0],"amount"=>$date_id[1]);
    //             $pay_type[]=$date_id[0];
    //         }
            
    //         if(in_array(10,$pay_type) && sizeof($pay_type)>1){//不记账结算不可用于复合结算
    //             $response = Lang::get("scs_error.order_pay_type_error_40042");
    //             break;
    //         }
    //         $amount=$order->amount-$order->discount_amount;
    //         //是否修改过订单支付金额
    //         $temp_balance_anount=$order->balance_amount>0?$order->balance_amount:0;
    //         if(floor($temp_balance_anount/100)!=$temp_amount){
    //             $response = Lang::get("scs_error.order_amount_error_40010");
    //             break;
    //         }

    //         $account = UserAccount::where('user_id',$userInfo->id)->first();
    //         //验证额度
    //         if($userInfo->type == 2 && (in_array(6,$pay_type) || in_array(8,$pay_type))){//企业挂账
    //             $credit=0;
    //             foreach($pay_array as $pa){
    //                 if($pa['pay_type']==6||$pa['pay_type']==8){
    //                     $credit+=$pa['amount'];
    //                 }
    //             }
    //             if(($account->balance + $account->credit-$credit) < 0){                  
    //                 $response = Lang::get("scs_error.order_user_notpay_40039");
    //                 return $response;
    //             }
    //         }
            
            
    //         return array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
           
            
    //     }while(false);
    //     Log::info("info", array("system" => "scs" ,"otherPay" => "accredit", 'input' =>Input::all() ,"output" => $response));
    //     return json_encode($response);
    // }



    /**
     * @Author:      lyt
     * @DateTime:    2016-10-25 16:44:06
     * @Description: 订单代付 执行
     */
    /**
     * @Author:      lyt
     * @DateTime:  2017-06-14 16:58:41
     * @Description: 修改代付执行  去掉支付信息 
     */
    public function otherPay(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "order_id"=>'required',
                // "type"=>'required',
                // "code"=>'numeric',
                // 'pays'=>"required",
                "pay_user_id"=>'required',
                "user_car_id"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            //验证身份
            // if(Input::get('type')==1){
            //     $sc=SCUser::find(Input::get('id'));
            //     if(is_null($sc)){
            //         $response = Lang::get("scs_error.order_otherpay_checkuser_error_42002");
            //         break;
            //     }
            //     //判断验证码是否存在
            //     $record = UserCheckCodeUpgrade::where('business_id',Input::get("order_id"))->where("business_type","other_pay")->where("phone",$sc->phone)->first();
            //     if(is_null($record)){ //没有记录
            //         $response = Lang::get("error.user_login_checkcode_null_1012");
            //         break;
            //     }               
            //     if( time() > Common::datetime2Num($record->out_time_at) ){ //校验是否超过时限
            //         $response = Lang::get("error.user_login_checkcode_timeout_1013");
            //         break;
            //     }       
               
            //     if($record->check_code != Input::get('code')){ //校验验证码是否匹配
            //         $response = Lang::get("error.user_login_checkcode_error_1014");
            //         break;
            //     }
            // }else{
            //     $sc=SCUser::where('user_name',Input::get('username'))->where('password',strtoupper(md5(Input::get('password'))))->where('status',1)->first();
            //     if(is_null($sc)){
            //         $response = Lang::get("scs_error.scs_user_not_exiet21009");
            //         break;
            //     }
                
            // }
            // if($sc->title!=1){
            //     $response = Lang::get("scs_error.order_otherpay_checkuser_error_42003");
            //     break;
            // }
            //验证身份完毕
            $order=Orders::find(Input::get('order_id'));
            $userInfo=Users::find(Input::get("pay_user_id"));
            if(is_null($userInfo)||$userInfo->type==1){
                $response = Lang::get("scs_error.order_otherpay_payuser_error_42004");
                break;
            }
            if(is_null($order)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if($order->status!=1420||$order->order_type==2||$order->pay_user_id!=0){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_status_error_40024");
                break;
            }            
            if(Orders::isOutReturnOrders($order->order_id)){//是否有 未完成的出退库 记录
                $response = Lang::get("scs_error.order_out_return_error_40034");
                break;
            }
            if(in_array($order->status,array(1117,1217,1417))){//是否已结算
                $response = Lang::get("scs_error.order_status_error_40040");
                break;
            }       
            $op=OrderProduct::where("order_id",$order->order_id)->where("product_type","service_card")->where("status",1)->first();      
            if($op){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_otherpay_error_42007");
                break;
            } 
            //查看时候有支付记录
            $op=OrderPay::where("order_id",$order->order_id)->whereIn("status",array(0,1,5,7))->first();      
            if($op){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_pay_record_40112");
                break;
            } 
            /*6月 
                S10版本注释 新确认订单逻辑 用户记录用户支付用户信息
            */
            //记录订单代付记录
            $opr=new OtherPayRecord;
            $opr->order_id =$order->order_id;//
            $opr->autu_id =$userInfo->id;//
            $opr->user_car_id =Input::get("user_car_id");//
            $opr->create_by =$sc_user->id;//
            $opr->save();
            $order->pay_user_id=$userInfo->id;
            $order->save();
            /*6月 
                S10版本注释 新确认订单逻辑 增加订单结算状态
            */
            // $pays = json_decode(Input::get('pays'),1);
            // $pay_array=array();
            // $pay_type=array();
            // $temp_amount=0;
            // foreach ($pays as $_pay) {
            //     $date_id=explode(":",$_pay);
            //     $temp_amount+=$date_id[1];
            //     $pay_array[]=array("pay_type"=>$date_id[0],"amount"=>$date_id[1]);
            //     $pay_type[]=$date_id[0];
            // }
            
            // if(in_array(10,$pay_type) && sizeof($pay_type)>1){//不记账结算不可用于复合结算
            //     $response = Lang::get("scs_error.order_pay_type_error_40042");
            //     break;
            // }
            // $amount=$order->amount-$order->discount_amount;
            // //是否修改过订单支付金额
            // $temp_balance_anount=$order->balance_amount>0?$order->balance_amount:0;
            // if(floor($temp_balance_anount/100)!=$temp_amount){
            //     $response = Lang::get("scs_error.order_amount_error_40010");
            //     break;
            // }

            
            // //订单支付 记录账务
            // $response=Orders::otherPay($order->order_id,$pay_array,$userInfo->id,$sc_user->id,"sc",1417);
            // if($response["code"]!=0){
            //     break;
            // }

            // //记录代付验证信息 
            // $opr=new OtherPayRecord;
            // $opr->order_id =$order->order_id;//
            // $opr->autu_id =$userInfo->id;//
            // $opr->user_car_id =Input::get("user_car_id");//
            // $opr->create_by =$sc_user->id;//
            // $opr->save();

            // //更改用户车辆里程
            // if($order->order_type==1){
            //     $uci=UserCarInfo::find($order->user_car_id);
            //     ModifyCarsRecords::saveRecords($sc_user,$uci->id);
            //     $uci->mileage =$order->mileage;//
            //     $uci->save();
            // }
            // //订单反算金额
            // Orders::inverseOrder($order->order_id);
            
            // $order_flows = new OrderFlows;
            // $order_flows->order_id = $order->order_id;
            // $order_flows->status =1417;
            // $order_flows->user_id = $sc_user->id;
            // $order_flows->type = 'sc';
            // $order_flows->save();


            // if($order->order_type==1){//如果是 服务单 才有下面的逻辑
            //     //删除订单停车场记录
            //     MaintenancePark::where('order_id',Input::get('order_id'))->delete();

            //     //腾出车位
            //     $mscs=MaintenanceStationCarStatus::where('order_id',Input::get('order_id'))->update(array("car_no"=>"","status"=>0,"car_model_id"=>0,"order_id"=>0,'mileage'=>0,'vin_code'=>'','insurance'=>''));
            //     $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));


            //     /*发送短信*/
            //     //SendMessage::sendSms('custom_pay_order_status',$order->order_id);

            //     /*邀请完成订单送券*/
            //     Coupons::invite($order->order_id);
            // }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"otherPay" => "accredit", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:  2017-06-14 18:34:34
     * @Description: 用于取消订单的支付用户信息
     */
    public function cancel_payuser(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "order_id"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
           
            //验证身份完毕
            $order=Orders::find(Input::get('order_id'));
            
            if(is_null($order)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if($order->status!=1420||$order->order_type==2){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_status_error_40024");
                break;
            }      

            //查看时候有支付记录
            $op=OrderPay::where("order_id",$order->order_id)->whereIn("status",array(0,1,5,7))->first();      
            if($op){//订单状态是否为服务结束状态
                $response = Lang::get("scs_error.order_pay_record_40112");
                break;
            }  
            OtherPayRecord::where("order_id",$order->order_id)->delete();            
            $order->pay_user_id=0;
            $order->save();    

            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"otherPay" => "accredit", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    
}